package com.shangxia.basic.common.mybatis.dynamicsource;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @ProjectName: MyDemo_zy
 * @ClassName: DynamicDataSourceAspect
 * @Time: 2020-04-01 20:21
 * @Author: zhou24
 * @Description:
 * @Experience:
 */
@Aspect
@Order(-1)
@Component
@Slf4j
public class DynamicDataSourceAspect {
    @Before("@annotation(ds)")
    public void changeDataSource(JoinPoint point, DataSourceType ds) {
        System.out.println("===Aspect===");
        if (!DynamicDataSourceContextHolder.containsDataSource(ds.value())) {
            log.error("数据源[{}]不存在，使用默认数据源{}", ds.value(), DynamicDataSourceContextHolder.getDataSourceType());
        } else {
            DynamicDataSourceContextHolder.setDataSourceType(ds.value());
        }
    }

    @After("@annotation(ds)")
    public void restoreDataSource(JoinPoint point, DataSourceType ds) {
        System.out.println("===Aspect===");
        DynamicDataSourceContextHolder.clearDataSourceType();
        log.debug("Revent DataSource {} {}", ds.value(), DynamicDataSourceContextHolder.getDataSourceType());
    }
}
